package com.aforce3.trailertracer;

import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.vecmath.Point3d;
import javax.vecmath.Vector3d;

import com.aforce3.trailertracer.scenes.SceneGroup;
import com.aforce3.trailertracer.scenes.Triangle;

public class FrameReader
{
	BufferedImage image;
	Camera camera;
	SceneGroup scene = new SceneGroup();

	List<Point3d> verticies = new ArrayList<Point3d>();

	public Frame read(File file)
	{
		try
		{
			BufferedReader in = new BufferedReader(new FileReader(file));
			String str;
			while((str = in.readLine()) != null)
			{
				String[] alltokens = str.replaceAll("\\+", "").split("\\s+");
				List<String> legittokens = new ArrayList<String>();
				for(String token : alltokens) if(!token.matches("\\s+")) legittokens.add(token);
				process(legittokens.toArray(new String[0]));
			}
			in.close();
		}
		catch(IOException e)
		{
			throw new RuntimeException(e);
		}
		return new Frame(image, camera, scene);
	}

	public void process(String[] line)
	{
		if(line.length == 0 || line.length == 1) return; // It's a noop
		if(line[0].startsWith("#")) return; // It's a comment
		if("size".equals(line[0])) image = new BufferedImage(Integer.parseInt(line[1]), Integer.parseInt(line[2]), BufferedImage.TYPE_INT_RGB);
		if("camera".equals(line[0]))
		{
			Point3d position = new Point3d(Integer.parseInt(line[1]), Integer.parseInt(line[2]), Integer.parseInt(line[3]));
			Point3d lookat = new Point3d(Integer.parseInt(line[4]), Integer.parseInt(line[5]), Integer.parseInt(line[6]));
			Vector3d up = new Vector3d(Integer.parseInt(line[7]), Integer.parseInt(line[8]), Integer.parseInt(line[9]));
			double fov = (Integer.parseInt(line[10])/360.0) * (2 * Math.PI);
			camera = new Camera(position, lookat, up, fov);
		}
		if("vertex".equals(line[0])) verticies.add(new Point3d(Integer.parseInt(line[1]), Integer.parseInt(line[2]), Integer.parseInt(line[3])));
		if("tri".equals(line[0])) scene.add(new Triangle(verticies.get(Integer.parseInt(line[1])), verticies.get(Integer.parseInt(line[2])), verticies.get(Integer.parseInt(line[3]))));
	}

	public static void main(String[] args)
	{
		Frame frame;
		FrameReader frameReader = new FrameReader();
		if(args.length != 0) frame = frameReader.read(new File(args[0]));
		else frame = frameReader.read(new File("scene0.test"));
		
		System.out.println(frame.getCamera());

		FrameServer server = new FrameServer(frame);
		Renderer renderer = new Renderer(server);
		new Display(server, renderer);
		renderer.start();
	}
}
